package org.csu.mypetstorems.interceptors;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.csu.mypetstorems.result.Result;
import org.csu.mypetstorems.util.JwtUtil;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.data.redis.core.StringRedisTemplate;
//import org.springframework.data.redis.core.ValueOperations;
import org.csu.mypetstorems.util.ThreadLocalUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {
//    @Autowired
//    private StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object handler) throws Exception{
        String token = request.getHeader("Authorization");
        //验证token
        try {
            //从redis中获取相同的token
//            ValueOperations<String,String> operations = stringRedisTemplate.opsForValue();
//            String redisToken = operations.get(token);
//            if(redisToken == null){
//                throw new RuntimeException();
//            }
            //这样就会一直存放?
            Map<String, Object> claims = JwtUtil.parseToken(token);
            ThreadLocalUtil.set(claims);
            return true;//放行
        } catch (Exception e){
            //http响应状态码为401
            response.setStatus(401);
            return false;//不放行
        }
    }
}
